'use client';

import type { TMetadata } from '@/types';
import { useSearchParams } from 'next/navigation';
import { useInfiniteQuery } from '@tanstack/react-query';
import { clientQuerySectionDetailsById } from '@/services/api';
import type {
  IPost,
  IQueryParams,
  ISectionDetails,
  ITag,
  ITagGroup,
  IUser,
} from '@/interfaces';
import Link from 'next/link';
import classNames from 'classnames';
import LoadPage from '@/app/[locale]/load/load';
import ErrorPage from '@/app/[locale]/error/error';
import { toRelativeTime } from '@/lib/tool';
import { useEffect, useState } from 'react';
import useToast from '@/hooks/useToast';
import useContentLayer from '@/hooks/useContentLayer';
import FooterH5IcpPage from '@/app/[locale]/mobile/footerH5Icp';
import FooterH5Page from '@/app/[locale]/mobile/footerH5';
import PostSectionIdH5Page from '@/app/[locale]/mobile/sections/[id]/post';
import { SectionIdH5PageContext } from '@/contexts/mobile/sectionId';
import Nodata from '@/app/[locale]/common/nodata/nodata';

export default function SectionIdH5Page({ metadata }: { metadata: TMetadata }) {
  return (
    <>
      <SectionId metadata={metadata} />
      <FooterH5IcpPage metadata={metadata} />
      <FooterH5Page metadata={metadata} />
    </>
  );
}

const SectionId = ({ metadata }: { metadata: TMetadata }) => {
  const { show } = useToast();
  const [isClickLoadMore, setIsClickLoadMore] = useState(false);
  const [pages, setPages] = useState<IPost[]>(
    (metadata.all['sectionId'].v as ISectionDetails).data?.content ?? [],
  );

  const clientQuerySectionDetailsByIdQuery = useInfiniteQuery(
    metadata.all['sectionId'].k,
    async (context) => {
      return (await clientQuerySectionDetailsById({
        id: context.queryKey[3],
        query: {
          ...(context.queryKey[5] as IQueryParams),
          ...context.pageParam,
        },
      })) as ISectionDetails;
    },
    {
      enabled: isClickLoadMore,
      keepPreviousData: true,
      getPreviousPageParam: (firstPage) => {
        if (firstPage.data && firstPage.data.pageable.previous) {
          return {
            page: Math.max(firstPage.data.pageable.page - 1, 0),
          };
        }
      },
      getNextPageParam: (lastPage) => {
        if (lastPage.data && lastPage.data.pageable.next) {
          return {
            page: Math.min(
              lastPage.data.pageable.page + 1,
              lastPage.data.pageable.pages,
            ),
          };
        }
      },
      initialData: () => {
        if (metadata.all['sectionId']) {
          return {
            pages: [metadata.all['sectionId'].v as ISectionDetails],
            pageParams: [
              {
                page: Math.max(
                  ((metadata.all['sectionId'].k[5] as IQueryParams).page ?? 1) -
                    1,
                  0,
                ),
              },
            ],
          };
        }
      },
    },
  );

  useEffect(() => {
    if (clientQuerySectionDetailsByIdQuery.data) {
      setPages(
        clientQuerySectionDetailsByIdQuery.data.pages
          .flatMap((item) => item.data?.content ?? [])
          .map((item) => {
            item._contentUpdatedOnText = toRelativeTime(item.contentUpdatedOn);
            return item;
          }),
      );
    }
  }, [clientQuerySectionDetailsByIdQuery.data]);

  async function onClickLoadMore() {
    setIsClickLoadMore(true);

    try {
      await clientQuerySectionDetailsByIdQuery.fetchNextPage();
    } catch (e) {
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  if (clientQuerySectionDetailsByIdQuery.data) {
    const sectionData = clientQuerySectionDetailsByIdQuery.data.pages[0];

    return (
      <SectionIdH5PageContext.Provider
        value={{
          metadata,
        }}
      >
        <div className="col p-2">
          <div className="card rounded-5 border-0">
            <div className="card-body">
              <div className="vstack gap-4">
                <Top
                  name={sectionData.basic.name}
                  content={sectionData.content}
                  admins={sectionData.admins}
                  metadata={metadata}
                />

                <TagGroups
                  id={sectionData.basic.id}
                  items={sectionData.tagGroups}
                />

                <Tags id={sectionData.basic.id} items={sectionData.tags} />

                <PostSectionIdH5Page
                  items={pages}
                  isDisabled={
                    !clientQuerySectionDetailsByIdQuery.hasNextPage ||
                    clientQuerySectionDetailsByIdQuery.isFetchingNextPage
                  }
                  isFetchingNextPage={
                    clientQuerySectionDetailsByIdQuery.isFetchingNextPage
                  }
                  onClickLoadMore={onClickLoadMore}
                />

                {pages.length === 0 && <Nodata />}
              </div>
            </div>
          </div>
        </div>
      </SectionIdH5PageContext.Provider>
    );
  }

  if (clientQuerySectionDetailsByIdQuery.error) {
    return <ErrorPage error={clientQuerySectionDetailsByIdQuery.error} />;
  }

  return <LoadPage />;
};

const Top = ({
  name,
  content,
  admins,
  metadata,
}: {
  name: string;
  content: string | undefined;
  admins: IUser[];
  metadata: TMetadata;
}) => {
  useContentLayer({
    dep: content,
    metadata,
  });

  return (
    <div className="vstack gap-4">
      <div className="vstack gap-2">
        <h1 className="fs-4 card-title d-flex align-items-center" title={name}>
          <span>{name}</span>
        </h1>

        <div className="card-subtitle d-flex flex-nowrap text-nowrap overflow-x-auto pb-2">
          {admins.map((item, index) => {
            return (
              <div key={item.id} className="p-1">
                <Link
                  href={`/users/${item.id}`}
                  className="text-muted text-decoration-none text-decoration-underline-hover"
                >
                  {item.alias}
                </Link>
                {index !== admins.length - 1 && '、'}
              </div>
            );
          })}
        </div>
      </div>

      {content && (
        <div
          className="clearfix content-layer text-break"
          dangerouslySetInnerHTML={{ __html: content }}
        />
      )}
    </div>
  );
};

const TagGroups = ({ id, items = [] }: { id: number; items?: ITagGroup[] }) => {
  const urlSearchParams = useSearchParams();
  const activeTagGroupIndex =
    urlSearchParams.get('tagGroupId') || urlSearchParams.get('tgId');
  const activeTagIndex =
    urlSearchParams.get('tagId') || urlSearchParams.get('tId');

  return (
    <>
      {items.length > 0 && (
        <>
          {items.map((item) => {
            return (
              <div key={item.id} className="hstack gap-3 mb-3">
                <Link
                  href={`/sections/${id}`}
                  className="badge text-bg-light fs-6 text-decoration-none fw-normal text-decoration-underline-hover"
                >
                  {item.name}
                </Link>

                {(item.tags || []).map((item2) => {
                  return (
                    <Link
                      key={item2.id}
                      href={`/sections/${id}?tagGroupId=${item.id}&tagId=${item2.id}`}
                      className={classNames(
                        'badge fs-6 text-decoration-none fw-normal text-decoration-underline-hover',
                        activeTagGroupIndex === item.id + '' &&
                          activeTagIndex === item2.id + ''
                          ? 'text-bg-secondary'
                          : 'text-bg-light',
                      )}
                    >
                      {item2.name}
                    </Link>
                  );
                })}
              </div>
            );
          })}
        </>
      )}
    </>
  );
};

const Tags = ({ id, items = [] }: { id: number; items?: ITag[] }) => {
  const urlSearchParams = useSearchParams();
  const activeTagIndex =
    urlSearchParams.get('tagId') || urlSearchParams.get('tId');

  return (
    <>
      {items.length > 0 && (
        <div className="hstack gap-3">
          <Link
            href={`/sections/${id}`}
            className="badge text-bg-light fs-6 text-decoration-none fw-normal text-decoration-underline-hover"
          >
            全部
          </Link>

          {items.map((item) => {
            return (
              <Link
                key={item.id}
                href={`/sections/${id}?tagId=${item.id}`}
                className={classNames(
                  'badge fs-6 text-decoration-none fw-normal text-decoration-underline-hover',
                  activeTagIndex === item.id + ''
                    ? 'text-bg-secondary'
                    : 'text-bg-light',
                )}
              >
                {item.name}
              </Link>
            );
          })}
        </div>
      )}
    </>
  );
};
